package com.cnsuning.jobtool.db22db2;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class GenerateCountSql {
    /**
     * 配置路径
     */
    String configPath = "src/test/java/com/cnsuning/jobtool/db22db2/tables.json";
    /**
     * 生成配置
     */
    String configJson;

    /*
      * 生成文件路径
     */
    String finalFilePath = "C:\\Users\\徐兴兴\\Desktop\\sit环境db2 ddl\\genarateCount\\genarateCount";

    /**
     * sql模板文件
     */
    String templeteSql;

    @Before
    public void setup()
    {
        try {
            configJson = FileUtils.readFileToString(new File(configPath),"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }


        templeteSql = "UNION ALL SELECT count(0) FROM %s ";

    }

    @Test
    public void generate()
    {
        List<ConfigBean> configList = JSON.parseArray(configJson,ConfigBean.class);
            for (int i = 0; i < configList.size(); i++) {
                ConfigBean config = configList.get(i);
                String tableNames = config.getTableNames();
                String[] tables = tableNames.split(",");
                String dbFileName = finalFilePath+"_db"+(i+1)+".sql";
                File file = new File(dbFileName);
                if (file.exists())
                {
                    file.delete();
                }
                for (int j= 0;j < tables.length;j++)
                {
                    String tableName = tables[j];
                    try {
                        if (j == 0)
                        {
                            String tempString = String.format(templeteSql,tableName).substring(10);
                            FileUtils.writeStringToFile(file,tempString,"utf-8",true);
                        }else{
                            String tempString = String.format(templeteSql,tableName);
                            FileUtils.writeStringToFile(file,tempString,"utf-8",true);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
}
